package com.sdry.web.controller.hpf;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.sdry.model.hpf.Page;
import com.sdry.model.hpf.Product;
import com.sdry.service.hpf.ProductService;
import com.sdry.utils.ResponseUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 * @ClassName: ProductController 
 * @Description:产品Conrtroller
 * @Author hpf
 * @Date 2018年9月20日 下午2:22:33 
 * @version 1.0
 */
@RequestMapping(value="/productMana")
@Controller
public class ProductController {

	@Resource
	private ProductService productService;
	
	/**
	 * 分页查询产品信息
	 * @param page 分页条件
	 * @param product 查询条件
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping(value="/listPageProduct")
	public void listPageProduct(Page page,Product product,HttpServletResponse response) throws Exception{
		Map<String, Object> map = new HashMap<>();
		map.put("limit", page.getLimit());
		map.put("page", page.getPage());
		if (product.getPname() != null) {
			map.put("pname", product.getPname());
		} else {
			map.put("pname", "");
			product.setPname("");
		}
		int count = productService.countProduct(product);
		List<Product> productList = productService.listPageProduct(map);
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(productList, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 保存产品信息
	 * @param product
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping(value="/saveProduct")
	public void saveProduct(Product product,HttpServletResponse response) throws Exception{
		int isSuccess = 0;
		if (product.getPid() == null || "".equals(product.getPid())) {
			isSuccess = productService.insertProduct(product);
		} else {
			isSuccess = productService.updateProduct(product);
		}
		ResponseUtil.write(response, isSuccess);
	}
	
	/**
	 * 删除产品信息
	 * @param pid 产品ID组成的字符串
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping(value="/deleteProduct")
	public void deleteProduct(@RequestParam("str") String str,HttpServletResponse response) throws Exception{
		int isSuccess = productService.deleteProduct(str);
		ResponseUtil.write(response, isSuccess);
	}
	
	/**
	 * 校验是否删除产品
	 * @param str 产品ID组成的字符串
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping(value="/deleteProductOfVerify")
	public void deleteProductOfVerify(@RequestParam("str") String str,HttpServletResponse response) throws Exception{
		int isSuccess = productService.deleteProductOfVerify(str);
		ResponseUtil.write(response, isSuccess);
	}
}
